﻿using Vben.Base.Sys.Org.Dept;
using Vben.Base.Sys.Org.User.bo;

namespace Vben.Base.Sys.Org.User;

[Service]
public class SysOrgUserService : BaseMainService<SysOrgUser>
{
    public SysOrgUserService(SqlSugarRepository<SysOrgUser> repo)
    {
        base.repo = repo;
    }

    public new async Task InsertAsync(SysOrgUser user)
    {
        user.id = YitIdHelper.NextId() + "";
        // user.pacod = SecureUtils.PasswordEncrypt(user.pacod);
        // user.pacod = SecureUtils.PasswordEncrypt(user.pacod);
        if (user.depid != null)
        {
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == user.depid).Select(it => it.tier).SingleAsync();
            user.tier = deptTier + "_" + user.id;
        }
        repo.Context.Ado.BeginTran();
        await base.InsertAsync(user);
        await repo.Context.Insertable(new SysOrg { id = user.id, name = user.name, type = 8 }).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }

    public new async Task UpdateAsync(SysOrgUser user)
    {
        if (user.depid != null)
        {
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == user.depid).Select(it => it.tier).SingleAsync();
            user.tier = deptTier + "_" + user.id;
        }
        repo.Context.Ado.BeginTran();
        await base.UpdateAsync(user);
        await repo.Context.Updateable(new SysOrg { id = user.id, name = user.name, type = 8 })
            .UpdateColumns(it => new { it.name }).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }

    public async Task ResetPacod(IdPacodBo bo)
    {
        // bo.pacod = SecureUtils.PasswordEncrypt(bo.pacod);
        string sql = "update sys_org_user set pacod=@pacod where id=@id";
        await repo.Context.Ado.ExecuteCommandAsync(sql, new { id = bo.id, pacod = bo.pacod });
    }

    public async Task ChangeAvtag(IdAvtagBo bo)
    {
        string sql = "update sys_org_user set avtag=@avtag where id=@id";
        await repo.Context.Ado.ExecuteCommandAsync(sql, new { id = bo.id, avtag = bo.avtag });
    }
}